"""
Copyright (c) 2023 - present SKbioinfo
"""
import pandas as pd
from flask import request,jsonify,current_app
from flask_restful import Resource
from flask_jwt_extended import jwt_required
'''URL:/api/reportCreator/ReportSample/ReportSampleBySheet'''
class interfaceReportSampleBySheet(Resource):
    def _grouped_data(self,data:list,key:str):
        grouped={}
        for item in data:
            if key in item:
                grouped_value=item[key]
                if grouped_value not in grouped:
                    grouped[grouped_value]=[]
                grouped[grouped_value].append(item)
        results = [ 
            {"group":value[0]["group"],"sample_name":value[0]["sample"] + " & " + value[1]["sample"]}
            for key,value in grouped.items()
        ]
        return results
    @jwt_required()
    def get(self):
        try:
            run_id=request.args.get('run_id')
            base_dir=current_app.config.get("BASE_DIR")
            time_dir=request.args.get('time').split()[0]
            path=f'{base_dir}/results/{time_dir}/{run_id}/{run_id}_samplesheet.csv'
            df=pd.read_csv(path)
            sample_sheet=[row.to_dict() for index,row in df.iterrows()]
            groups=self._grouped_data(sample_sheet,"group")
            response=jsonify(groups)
            response.status=202
            return response  
        except Exception as e:
            response=jsonify({})
            response.status=404
            return response
 
class interfaceReportSampleSheetByPages(Resource):
    def get(self):
        try:
            page=int(request.args.get('page'))
            limit=int(request.args.get('limit'))
            run_id=request.args.get('run_id')
            base_dir=current_app.config.get("BASE_DIR")
            time_dir=request.args.get('time').split()[0]
            path=f'{base_dir}/results/{time_dir}/{run_id}/{run_id}_samplesheet.csv'
            df=pd.read_csv(path)
            results=[]
            for index,row in df.iterrows():
                results.append({
                    "sample":row["sample"],
                    "group":row["group"],
                    "short_reads_1":row["short_reads_1"],
                    "short_reads_2":row["short_reads_2"]
                })
            total=len(results)
            results_slice=results[(page-1)*limit:page*limit]
            response=jsonify({"total":total,"data":results_slice})
            response.status=202
            return response
        except Exception as e:
            response=jsonify({})
            response.status=404
            return response
        


